const db = uniCloud.database();
const { guid } = require('../../common/utils');
const { config } = require('../../config/index');
const { chapterList } = require('../list/index');
module.exports = async function(options = {}) {
	const { characterId, uid, groupName = '学习小组' } = options;
	if (!uid || !characterId) {
		throw new Error('非法操作');
	}
	// 获取没有重复的id
	async function getGroupId(character) {
		const groupId = Number(guid(6, null, null, true));
		const findDataRes = await db.collection('a-dz-group-list').where({ groupId }).get({ getOne: true });
		if (findDataRes.data.length) {
			return getGroupId();
		}
		return groupId;
	}
	let [configRes, groupCode, allChapters, characterList] = await Promise.all([
		config(),
		getGroupId(),
		chapterList({ uid }),
		db.collection('a-dz-character-list').where({ characterId }).get({ getOne: true })
	])
	const { kpm = 600, wpm = 120, successWpm = 120, accuracy = 100, accuracyKpm = 100, learningTime = 15 } = configRes;
	const chapters = allChapters.data.filter(item => item.type == 'DEFAULT').map(item => {
		return item.chapter;
	})
	if (characterList.data.length && characterList.data[0].type != 'TEACHER') {
		throw new Error('非法操作');
	}
	const addParams = {
		characterId,
		uid,
		groupCode: String(groupCode),
		groupName,
		status: 'UN_ACTIVATED',
		logo: 'https://static01.type.fun/group/group-logo-9.png',
		kpm,
		wpm,
		successWpm,
		accuracy,
		accuracyKpm,
		learningTime,
		chapters,
		chapters_custom: [],
		createdTime: Date.now()
	}
	await db.collection('a-dz-group-list').add(addParams);
	return {
		code: 0,
		data: addParams,
		msg: '创建成功'
	};
}